#! /bin/sh

export PATH=$PATH:/mnt/conf/bin

for i in /usr/conf/lib/*; do
    file=${i##*/}
    if [ ! -f /usr/lib/$file ]; then
        ln -s /usr/conf/lib/$file /usr/lib
    fi
done

hostname=`hostname`

if [ ! -f /usr/conf/etc/${hostname}.db ]; then
    mv /usr/conf/etc/seqiot.db /usr/conf/etc/${hostname}.db
fi

if [ ! -f /etc/${hostname}.db ]; then
  ln -s /usr/conf/etc/${hostname}.db /etc
fi

if [ ! -f /etc/thingmodel.db ]; then
  ln -s /usr/conf/etc/thingmodel.db /etc
fi

productKey=`fw_printenv -n product_key`
deviceName=`fw_printenv -n device_name`
deviceSecret=`fw_printenv -n device_secret`

if [ ! -f /mnt/userfs/home/remote_terminal.json ]; then
    cat /etc/remote_terminal.json.template | sed "s/{productKey}/${productKey}/g" | sed "s/{deviceName}/${deviceName}/g" | sed "s/{deviceSecret}/${deviceSecret}/g" > /mnt/userfs/home/remote_terminal.json
fi

if [ ! -f /etc/mosquitto.conf ]; then
    timestamp='date +%s'
    password="$(echo -n "clientId${productKey}.${deviceName}deviceName${deviceName}productKey${productKey}timestamp${timestamp}" | openssl sha256 -hmac ${deviceSecret} -r | awk '{print $1}')"
    cat /etc/mosquitto.conf.template | sed "s/{productKey}/${productKey}/g" | sed "s/{deviceName}/${deviceName}/g" | sed "s/{timestamp}/${timestamp}/g" | sed "s/{password}/${password}/g" > /etc/mosquitto.conf
fi
